package com.ambulance.framework.security.service;

import com.ambulance.common.enums.UserStatus;
import com.ambulance.common.exception.BaseException;
import com.ambulance.common.exception.CustomException;
import com.ambulance.common.utils.SecurityUtils;
import com.ambulance.common.utils.StringUtils;
import com.ambulance.framework.security.LoginUser;
import com.ambulance.project.biz.entity.*;
import com.ambulance.project.biz.enums.Role;
import com.ambulance.project.biz.service.*;
import com.ambulance.project.system.domain.SysUser;
import com.ambulance.project.system.service.ISysUserService;
import com.ambulance.utils.CommonUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;

/**
 * 用户验证处理
 *
 * @author zhao
 */
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DispatchNoticeService dispatchNoticeService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private NurseService nurseService;

    @Autowired
    private SysCacheService sysCacheService;

    @Autowired
    private DispatchService dispatchService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //验证用户
        String header = username.substring(0, 3);
        username = username.substring(4, username.length());
        //管理后台和web大屏医院主体登陆
        SysUser user = null;
        LoginUser loginUser = null;
        switch (header) {
            //管理平台和大屏
            case "MGT":
                user = userService.selectUserByUserName(username);
                if (StringUtils.isNull(user)) {
                    log.info("登录用户：{} 不存在.", username);
                    throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
                } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                    log.info("登录用户：{} 已被删除.", username);
                    throw new BaseException("对不起，您的账号：" + username + " 已被删除");
                } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                    log.info("登录用户：{} 已被停用.", username);
                    throw new BaseException("对不起，您的账号：" + username + " 已停用");
                }
                loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
                break;
            case "BWE":
                user = userService.selectUserByPhone(username);

                loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
                break;
            case "TER":
                //外援ios或者安卓登陆 手机验证码登陆
                SysCache byPhone = sysCacheService.getByPhone(username);
                if (CommonUtils.checkNull(byPhone)) {
                    log.info("登录用户：{} 验证码已失效.", username);
                    throw new BaseException("验证码已失效");
                }
                Hospital hospital = hospitalService.getOne(new QueryWrapper<Hospital>().eq("relation_phone", username));
                if (StringUtils.isNull(hospital)) {
                    throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
                }
                user = new SysUser();
                user.setUserId(new Long(hospital.getUid()));
                user.setPassword(SecurityUtils.encryptPassword(byPhone.getVerifyCode()));
                user.setUserName(hospital.getTreatAccount());
                user.setNickName(hospital.getHospitalName());
                //临时装载外援标识
                user.setDeptId(new Long(hospital.getHospitalID()));
                loginUser = new LoginUser(user, new HashSet<>());
                break;
            case "WYD":
                //外援登陆 账号密码登录
                hospital = hospitalService.getOne(new QueryWrapper<Hospital>().eq("relation_phone", username));

                //User account = bizUserService.getOne(new QueryWrapper<User>().eq("account", username));
                if (StringUtils.isNull(hospital)) {
                    throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
                }
                user = new SysUser();
                user.setUserId(new Long(hospital.getUid()));
                user.setPassword(hospital.getPasswd());
                user.setUserName(hospital.getTreatAccount());
                user.setNickName(hospital.getHospitalName());
                user.setDeptId(new Long(hospital.getHospitalID()));
                loginUser = new LoginUser(user, new HashSet<>());
                break;
            case "PAD":
            case "MVR":
                //医生和护士登陆pad和vr， token登陆特殊处理
//                QueryWrapper<DispatchNotice> noticeQueryWrapper = new QueryWrapper<>();
//                noticeQueryWrapper.eq("token", username).eq("status", 1).last("LIMIT 1");
//                DispatchNotice noticeServiceOne = dispatchNoticeService.getOne(noticeQueryWrapper, false);
//                if (CommonUtils.checkNull(noticeServiceOne)) {
//                    throw new CustomException("验证码不存在");
//                }

                //医生护士手机号登录
                QueryWrapper<Doctor> doctorQueryWrapper = new QueryWrapper<>();
                doctorQueryWrapper.eq("phone",username);
                doctorQueryWrapper.eq("status",0);
                doctorQueryWrapper.last("limit 1");
                Doctor doctor = doctorService.getOne(doctorQueryWrapper);
                Nurse nurse = null;
                if (doctor == null) {
                    QueryWrapper<Nurse> nurseQueryWrapper = new QueryWrapper<>();
                    nurseQueryWrapper.eq("phone",username);
                    nurseQueryWrapper.eq("status",0);
                    nurseQueryWrapper.last("limit 1");
                    nurse = nurseService.getOne(nurseQueryWrapper);
                    if (nurse == null) {
                        throw new CustomException("用户不存在");
                    }
                }

                // 查询调度信息
                QueryWrapper<DispatchNotice> noticeQueryWrapper = new QueryWrapper<>();
                if (doctor != null) {
                    noticeQueryWrapper.eq("usrID", doctor.getDoctorID());
                    noticeQueryWrapper.eq("type",1);
                }
                if (nurse != null) {
                    noticeQueryWrapper.eq("usrID", nurse.getNurseID());
                    noticeQueryWrapper.eq("type",2);
                }
                noticeQueryWrapper.eq("status", 1);
                noticeQueryWrapper.orderByDesc("noticeID");
                noticeQueryWrapper.last("LIMIT 1");
                DispatchNotice noticeServiceOne = dispatchNoticeService.getOne(noticeQueryWrapper, false);
                if (CommonUtils.checkNull(noticeServiceOne)) {
                    throw new CustomException("调度信息不存在");
                }

                Dispatch dispatch = dispatchService.getById(noticeServiceOne.getDispatchID());
                if (CommonUtils.checkNull(dispatch)) {
                    throw new CustomException("调度信息不存在");
                }


                user = new SysUser();

                //pid临时装载调度标识
                user.setPid(noticeServiceOne.getDispatchID());
                if (doctor != null) {
                    user.setUserId(doctor.getUid().longValue());
                    user.setDeptId(doctor.getDoctorID().longValue());
                    user.setPassword(doctor.getPassword());
                    user.setUserName(doctor.getHospital());
                    user.setNickName(doctor.getName());
                    user.setSex(Role.DOCTOR.name());
                } else {
                    user.setUserId(nurse.getUid().longValue());
                    user.setPassword(nurse.getPassword());
                    user.setDeptId(nurse.getNurseID().longValue());
                    user.setSex(Role.NURSE.name());
                    user.setUserName(nurse.getHospital());
                    user.setNickName(nurse.getName());
                }
                loginUser = new LoginUser(user, new HashSet<>());
                break;
            default:
                throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        return loginUser;
    }

}
